<?php
class Sys_Jssdk
{
  private $appId;
  private $appSecret;

  public function __construct() 
  {
        $this->appId = 'wxb45529d87242d718';
        $this->appSecret = 'c3e776fe22fd464fe1c9db05e78b165c';
  }

  public function getSignPackage()
  {
    $jsapiTicket = $this->getJsApiTicket();
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    $timestamp = time();
    $nonceStr = $this->createNonceStr();
    $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
    $signature = sha1($string);
    $signPackage = array(
                          "appId"     => $this->appId,
                          "nonceStr"  => $nonceStr,
                          "timestamp" => $timestamp,
                          "url"       => $url,
                          "signature" => $signature,
                          "rawString" => $string
                      );
    return $signPackage; 
  }

  private function createNonceStr($length = 16)
  {
      $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
      $str = "";
      for ($i = 0; $i< $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
      }
      return $str;
  }

  private function getJsApiTicket()
  {
    $data = json_decode(file_get_contents("jsapi_ticket.json"));
    if($data->expire_time < time()) 
    {
        $accessToken = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
        $res = json_decode($this->httpGet($url));
        $ticket = $res->ticket;
        if($ticket)
        {
            $data->expire_time = time() + 7000;
            $data->jsapi_ticket = $ticket;
            $fp = fopen("jsapi_ticket.json", "w");
            fwrite($fp, json_encode($data));
            fclose($fp);
        }
    }else{
        $ticket = $data->jsapi_ticket;
    }
    return $ticket;
  }

  function getAccessToken()
  {
      $data = json_decode(file_get_contents("access_token.json"));
      if($data->expire_time < time())
      {
          $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appId."&secret=".$this->appSecret;
          $res = json_decode($this->httpGet($url));
          $access_token = $res->access_token;
          if($access_token)
          {
              $data->expire_time = time() + 7000;
              $data->access_token = $access_token;
              $fp = fopen("access_token.json", "w");
              fwrite($fp, json_encode($data));
              fclose($fp);
          }
      }else{
          $access_token = $data->access_token;
      }

      return $access_token;
  }

  function httpGet($url, $data = null)
  {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_URL, $url);

    if(!empty($data)){
       curl_setopt($curl, CURLOPT_POST, 1);
       curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }

    $res = curl_exec($curl);
    curl_close($curl);

    return $res;
  }


  //注册成功推送信息
  function sentTemplateMessage()
  {
    $access_token = $this->getJsApiTicket(); //获取ACCESS_TOKEN
    $url = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=$access_token";
    //$data = ;
    httpGet($url, $data);
  } 

  /**
   * 注册成功消息模版
   * @param  [type] $wechat_id 微信用户openID
   * @param  [type] $serverUrl 服务器URL
   * @param  [type] $phone     用户手机号
   * @param  [type] $sn        用户编号
   * @param  [type] $regdate   注册时间
   * @return [type]            [description]
   */
  function registerSuccessTemplate($wechat_id, $serverUrl, $phone, $sn, $regdate )
  {
    $template=array(
                   'touser'=>$wechat_id,
                   'template_id'=>"evbMIPewWa8XcrqkYmGvHuSXktufLg9OAlIUB4YDmhY",
                   'url'=>$serverUrl,
                   'topcolor'=>"#7B68EE",
                   'data'=>array(
                             'first'=>array('value'=>urlencode("您好,您已注册成功。"),'color'=>"#743A3A"),
                             'phone'=>array('value'=>urlencode($phone),'color'=>'#EEEEEE'),
                             'sn'=>array('value'=>urlencode($sn),'color'=>'#EEEEEE'),
                             'regdate'=>array('value'=>urlencode($regdate),'color'=>'#EEEEEE'),
                             'remark'=>array('value'=>urlencode('感谢您的注册。'),'color'=>'#FFFFFF'),
                                )
                    );
     return $json_template=json_encode($template);
  }

   //推荐人推荐和投资成功推送信息
  function reSuccessTemplate($wechat_id, $serverUrl, $phone, $sn, $regdate )
  {
    $template=array(
                   'touser'=>$wechat_id,
                   'template_id'=>"evbMIPewWa8XcrqkYmGvHuSXktufLg9OAlIUB4YDmhY",
                   'url'=>$serverUrl,
                   'topcolor'=>"#7B68EE",
                   'data'=>array(
                             'first'=>array('value'=>urlencode("您好,您已注册成功。"),'color'=>"#743A3A"),
                             'phone'=>array('value'=>urlencode($phone),'color'=>'#EEEEEE'),
                             'sn'=>array('value'=>urlencode($sn),'color'=>'#EEEEEE'),
                             'regdate'=>array('value'=>urlencode($regdate),'color'=>'#EEEEEE'),
                             'remark'=>array('value'=>urlencode('感谢您的注册。'),'color'=>'#FFFFFF'),
                                )
                    );
     return $json_template=json_encode($template);
  }
  
  /**
   * 获取用户基本信息（包括UnionID机制）
   * subscribe 用户是否订阅该公众号标识，值为0时，代表此用户没有关注该公众号，拉取不到其余信息。
   * @return [type] [description]
   */
  function subscribeAfterMemberWechatInfo($openid)
  {
      $accessToken = $this->getAccessToken();
      $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$accessToken&openid=$openid&lang=zh_CN";
      return $res = Zend_Json::decode($this->httpGet($url));

  }

  /**
   * 网页授权获取用户基本信息
   * 注意：此access_token与基础支持的access_token不同
   * @return [type] [description]
   */
  function oauthAfterMemberWechatInfo($access_token, $openid)
  {
    $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
    return $res = Zend_Json::decode($this->httpGet($url));
  }

  /**
   * 通过code换取网页授权access_token
   * @param  [type] $code [description]
   * @return [type]       [description]
   */
  function oauthAccessToken($code)
  {
      $url ='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->appId.'&secret='.$this->appSecret.'&code='.$code.'&grant_type=authorization_code';
      return $res = Zend_Json::decode($this->httpGet($url));  
  }


  //批量获取用户基本信息
  //最多支持一次拉取100条。
  function batchGetWechatInfo($data)
  {
    $accessToken = $this->getAccessToken();
    $url ="https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=$accessToken";
    return $res = Zend_Json::decode($this->httpGet($url, $data));
  }

}